using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Redis_demo.Entities;
using StackExchange.Redis;

namespace Redis_demo.Controllers;

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    public readonly IConnectionMultiplexer _connectionMultiplexer;
    public readonly UserDbContext _dbContext;
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger,
         IConnectionMultiplexer connectionMultiplexer,
         UserDbContext dbContext)
    {
        _logger = logger;
        _connectionMultiplexer  = connectionMultiplexer;
        _dbContext = dbContext;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

    [HttpGet("RedisTest")]
    public string RedisTest()
    {
        var dataBase = _connectionMultiplexer.GetDatabase();
        if(!dataBase.KeyExists("name"))
        {
            dataBase.StringSet("name", "张三34433");
        }
        var name = dataBase.StringGet("name");
        //dataBase.SetAdd("user", new User(){Name="222",Age=12});
        // dataBase.StringGetSetExpiry("name",new DateTime().AddSeconds(10));
        return name;
    }

    [HttpGet("RedisTestForObject")]
    public string RedisTestForObject()
    {
        var dataBase = _connectionMultiplexer.GetDatabase();
        var user = new User1(){Name="222",Age=12};
        var josn = JsonSerializer.Serialize<User1>(user);
        dataBase.StringSet("user:200",josn);
        var name = dataBase.StringGet("user:200");
        //dataBase.SetAdd("user", new User(){Name="222",Age=12});
        // dataBase.StringGetSetExpiry("name",new DateTime().AddSeconds(10));
        // hash
        dataBase.HashSet("user:400","name","张思");
        dataBase.HashSet("user:400","age","12");

        return name;
    }

    [HttpGet("DbTest")]
    public void DbTest()
    {
        var user22 = new User(){Id="1",Name="frist",Phone="12323"};
        _dbContext.Users.Add(user22);
        _dbContext.SaveChanges();

    }
}

public class User1{
    public String Name{get;set;}
    public int Age { get; set; }
}
